package com.topscomm.qem.script;

import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.pojo.CboAttachmentEntity;
import com.topscomm.cbo.pojo.CboMessageMailEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.impl.CboAttachmentService;
import com.topscomm.cbo.service.impl.CboMessageMailService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.qem.QemScript;
import com.topscomm.qem.QemSystemConst;
import com.topscomm.qem.pojo.QemDutyDeptEntity;
import com.topscomm.qem.pojo.QemProblemAlertEntity;
import com.topscomm.qem.service.impl.QemDutyDeptService;
import com.topscomm.qem.service.impl.QemProblemAlertService;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.ParameterCache;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class qmsSendEmailScript extends QemScript {
    /**
     * 审批通过后，发送告警邮件
     *
     * @description:
     * @param service
     * @param entity
     * @author: hudueyong
     * @date: 2023年01月10日
     * @modify:
     */
    public void qmsSendEmail(ITapService service, TapEntity entity) {
        // 根据审批表获取问题告警信息
        CboApprovalNodeInsEntity cboApprovalNodeInsEntity = (CboApprovalNodeInsEntity) entity;
        QemProblemAlertService qemProblemAlertService = (QemProblemAlertService) SpringUtil.getBean("qemProblemAlertService");
        Map<String, Object> problemAlertInfo = qemProblemAlertService.queryMapById(cboApprovalNodeInsEntity.getSourceid()+"");
        // 发生邮件
        sendEmail(problemAlertInfo);
    }

    /**
     *  拼接表格
     *
     * @description:
     * @param service
     * @param entity
     * @author: hudueyong
     * @date: 2023年01月10日
     * @modify:Map<String, Object> problemAlertInfo, List<String> userEmails
     */
    public void sendEmail(Map<String, Object> problemAlertInfo){
        // 创建空邮件
        CboMessageMailEntity mailEntity = new CboMessageMailEntity();
        CboMessageMailService cboMessageMailService =  (CboMessageMailService)SpringUtil.getBean("cboMessageMailService");
        // @Value("${spring.profiles.active}")
        // 邮件来源类型
        mailEntity.setSourcetype(QemProblemAlertEntity.tableName);
        // 邮件来源ID
        mailEntity.setSourceid(ConvertUtil.convertToLong(problemAlertInfo.get("id")));
        //【问题等级】报警-【问题编号】-【问题发生环节】-【告警主题】
        //例如：重大异常报警-PA20221123003-交付验收-四川电能表全检验收合格率低（单相表）
        StringBufferProxy emailSubject = new StringBufferProxy();
        // 拼接邮件主题
        emailSubject.appendSingle("{0}报警-{1}-{2}-{3}",
                ConvertUtil.convertToString(problemAlertInfo.get("dispproblemgrading")),
                ConvertUtil.convertToString(problemAlertInfo.get("docno")),
                ConvertUtil.convertToString(problemAlertInfo.get("disphappennode")),
                ConvertUtil.convertToString(problemAlertInfo.get("warningtitle")));
        mailEntity.setSubject(emailSubject.toString());
        // 邮件内容
        mailEntity.setContent(formatEmailContent(problemAlertInfo));
        // 根据不同环境发生给不同用户
        // 正式发生给告警单提交人、复核人、风险排查负责人、问题分析负责人，问题归属产品线、牵头分析部门的提醒人和额外提醒收件箱
        // 开发、测试、仿真发送给系统参数配置的用户
        String active = ParameterCache.getValue("qmsActive","prod");
        if("dev".equals(active) || "test".equals(active) || "preprod".equals(active)){
            mailEntity.setReceivermails(ParameterCache.getValue("qmsProbelmAlertEmail"));
        } else {
            mailEntity.setReceivermails(queryReceiverMails(problemAlertInfo));
        }
        cboMessageMailService.insert(mailEntity);
    }

    /**
     *  获取接收人邮箱
     *
     * @description:
     * @param service
     * @param entity
     * @author: hudueyong
     * @date: 2023年01月11日
     * @modify:
     */
    public String queryReceiverMails(Map<String, Object> problemAlertInfo){
        QemProblemAlertEntity problemAlertEntity = new QemProblemAlertEntity();
        problemAlertEntity.convertFromMap(problemAlertInfo);
        StringBuilder receiverMails = new StringBuilder();
        // 额外接收人邮箱 123@topscomm.com,
        if(!ConvertUtil.convertToString(problemAlertEntity.getOthermails()).isEmpty()){
            receiverMails.append(ConvertUtil.convertToString(problemAlertInfo.get("othermails"))+",");
        }
        // 拼接人员，查询邮箱
        StringBuilder usercodes = new StringBuilder();
        // 申请人 '9927','6919'
        usercodes.append("'"+problemAlertEntity.getUsercode()+"',");
        // 风险排查负责人
        if(!ConvertUtil.convertToString(problemAlertEntity.getRiskmancode()).isEmpty()){
            usercodes.append("'"+problemAlertEntity.getRiskmancode()+"',");
        }
        // 问题分析负责人
        if(!ConvertUtil.convertToString(problemAlertEntity.getAssayercode()).isEmpty()){
            usercodes.append("'"+problemAlertEntity.getAssayercode()+"',");
        }
        // 复核人
        if(!ConvertUtil.convertToString(problemAlertEntity.getReviewmancode()).isEmpty()){
            usercodes.append("'"+problemAlertEntity.getReviewmancode()+"',");
        }
        // 项目经理
        if(!ConvertUtil.convertToString(problemAlertEntity.getProjectmanagercode()).isEmpty()){
            usercodes.append("'"+problemAlertEntity.getProjectmanagercode()+"',");
        }
        StringBufferProxy sql = new StringBufferProxy();
        // 查询牵头分析部门和产品线
        sql.appendSingle("code in ('{0}','{1}')",problemAlertEntity.getProductline(),problemAlertEntity.getDutydept());
        QemDutyDeptService qemDutyDeptService = (QemDutyDeptService) SpringUtil.getBean("qemDutyDeptService");
        List<QemDutyDeptEntity> qemDutyDeptEntities = qemDutyDeptService.queryByWhere(sql.toString());
        // 遍历牵头分析部门和产品线，提取部门的提醒人和额外邮箱
        for(QemDutyDeptEntity qemDutyDeptEntity : qemDutyDeptEntities){
            // 如果提醒人不为空，拼接提醒人
            if(!ConvertUtil.convertToString(qemDutyDeptEntity.getAlertusercodes()).isEmpty()){
                String alertUserCodes = "'" + Arrays.asList(qemDutyDeptEntity.getAlertusercodes().split(",")).stream().collect(Collectors.joining("','")) + "'";
                usercodes.append(alertUserCodes+",");
            }
            // 如果额外邮箱不为空，拼接额外邮箱
            if(!ConvertUtil.convertToString(qemDutyDeptEntity.getEmails()).isEmpty()){
                receiverMails.append(qemDutyDeptEntity.getEmails()+",");
            }
        }
        // 查询拼接的提醒人的邮箱
        CboUserService cboUserService = (CboUserService) SpringUtil.getBean("cboUserService");
        sql.clear();
        sql.appendSingle("code in ({0})",usercodes.substring(0,usercodes.length()-1));
        List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(sql.toString());
        String userEmails = cboUserEntities.stream().map(item -> item.getEmail()).collect(Collectors.joining(","));
        // 将拼接的提醒人的邮箱放到拼接的邮箱里
        receiverMails.append(userEmails);
        // 去重distinctString
        return distinctString(receiverMails.toString());
    }

    /**
     * @return void
     * @description: 字符串去重
     * @author: hdy
     * @date: 2023年01月11日
     * @modify:
     */
    public String distinctString(String str) {
        //创建一个集合
        List<String> distinctList = new ArrayList<>();
        //遍历数组往集合里存元素
        String[] strs = str.split(",");
        for (int i = 0; i < strs.length; i++) {
            //如果集合里面没有相同的元素才往里存
            if (distinctList.indexOf(strs[i])<0) {
                distinctList.add(strs[i]);
            }
        }
        return distinctList.stream().collect(Collectors.joining(","));
    }

    /**
     *  拼接表格，不含附件，拼接附件的方法在下方
     *
     * @description:
     * @param service
     * @param entity
     * @author: hudueyong
     * @date: 2023年01月10日
     * @modify:
     */
    public String formatEmailContent(Map<String, Object> problemAlertInfo){
        StringBuilder emailContent = new StringBuilder();
        String bpaQualityImprovementCatalog = ParameterCache.getValue("bpaQualityImprovementCatalog");
        emailContent.append("<div folat=\"left\">");
        emailContent.append("<div style='text-align: center;width:800px'><h2>"+ConvertUtil.convertToString(problemAlertInfo.get("warningtitle"))+"</h2></div>");
//        emailContent.append("<h1 align=\"center\">"+ ConvertUtil.convertToString(problemAlertInfo.get("warningtitle")) +"</h1>");
        emailContent.append("<table border='1' height=\"60%\" cellspacing='0' cellpadding='0' style='text-align: center;'></tableborder>");
        emailContent.append("<tr><th width=\"100px\">问题分级</th><th width=\"100px\">问题编号</th><th width=\"100px\">日期</th><th width=\"200px\">问题来源单号</th><th width=\"100px\">问题发生环节</th><th width=\"100px\">工序/试验类别</th><th width=\"100px\">IPD节点</th></tr>");
        emailContent.append("<tr><td>"+ ConvertUtil.convertToString(problemAlertInfo.get("dispproblemgrading")) +"</td>");
        emailContent.append("<td>"+ ConvertUtil.convertToString(problemAlertInfo.get("docno")) +"</td>");
        emailContent.append("<td>"+ ConvertUtil.convertToString(problemAlertInfo.get("docdate")).split(" ")[0] +"</td>");
        emailContent.append("<td>"+ ConvertUtil.convertToString(problemAlertInfo.get("sourcedocno")) +"</td>");
        emailContent.append("<td>"+ ConvertUtil.convertToString(problemAlertInfo.get("disphappennode")) +"</td>");
        emailContent.append("<td>"+ ConvertUtil.convertToString(problemAlertInfo.get("classes")) +"</td>");
        emailContent.append("<td>"+ ConvertUtil.convertToString(problemAlertInfo.get("dispipdnode")) +"</td></tr>");
        emailContent.append("<tr><th colspan=\"4\">产品名称</th><th>硬件版本</th><th>软件版本</th><th>MES条码</th></tr>");
        emailContent.append("<tr><td colspan=\"4\">"+ ConvertUtil.convertToString(problemAlertInfo.get("productname")) +"</td>");
        emailContent.append("<td>"+ ConvertUtil.convertToString(problemAlertInfo.get("hardwareversion")) +"</td>");
        emailContent.append("<td>"+ ConvertUtil.convertToString(problemAlertInfo.get("softwareversion")) +"</td>");
        emailContent.append("<td>"+ ConvertUtil.convertToString(problemAlertInfo.get("mesbarcode")) +"</td></tr>");
        emailContent.append("<tr><th colspan=\"4\">问题描述</th><th colspan=\"2\" >紧急处理方式</th><th>重复发生</th></tr>");
        emailContent.append("<tr><td colspan=\"4\" height=\"200px\" width=\"500px\" align=\"left\">"+ ConvertUtil.convertToString(problemAlertInfo.get("problemdesc")) +"</td>");
        emailContent.append("<td colspan=\"2\" rowspan=\"3\" width=\"200px\" align=\"center\">"+ ConvertUtil.convertToString(problemAlertInfo.get("emergenttreatment")) +"</td>");
        emailContent.append("<td rowspan=\"3\" width=\"100px\" align=\"center\">"+ ConvertUtil.convertToString(problemAlertInfo.get("disprepeat"))+"</td></tr>");
        emailContent.append("<tr><th colspan=\"4\">不良描述</th></tr>");
        emailContent.append("<tr><td colspan=\"4\" height=\"100px\" width=\"500px\" align=\"left\">"+ConvertUtil.convertToString(problemAlertInfo.get("rejects"))+"</td></tr>");
        emailContent.append("<tr><th colspan=\"2\">问题归属产品线</th><th colspan=\"2\">牵头分析部门</th><th>风险排查负责人</th><th>问题分析负责人</th><th>报警人</th></tr>");
        emailContent.append("<tr><td colspan=\"2\">"+ConvertUtil.convertToString(problemAlertInfo.get("productlinename")) +"</td>");
        emailContent.append("<td colspan=\"2\">"+ConvertUtil.convertToString(problemAlertInfo.get("dutydeptname")) +"</td>");
        emailContent.append("<td>"
                +ConvertUtil.convertToString(problemAlertInfo.get("riskman"))
                +'['+ ConvertUtil.convertToString(problemAlertInfo.get("riskmancode"))
                + ']'
                + "</td>");
        emailContent.append("<td>"
                +ConvertUtil.convertToString(problemAlertInfo.get("assayer"))
                +'['+ ConvertUtil.convertToString(problemAlertInfo.get("assayercode"))
                + ']'
                +"</td>");
        emailContent.append("<td>"
                +ConvertUtil.convertToString(problemAlertInfo.get("username"))
                +'['+ ConvertUtil.convertToString(problemAlertInfo.get("usercode"))
                + ']'
                +"</td></tr>");
        emailContent.append("</table>");
        emailContent.append("</br></br>");
        // 如果历史单据违反质量政策为空，违反内容也显示无
        emailContent.append("<strong>违反质量条款内容：</strong>"+(ConvertUtil.convertToString(problemAlertInfo
                .get("whetherqualitypolicy")).isEmpty() || QemSystemConst.QmsWhetherQualityPolicy.equals(ConvertUtil.convertToString(problemAlertInfo.get("whetherqualitypolicy"))) ? "无" : (ConvertUtil.convertToString(problemAlertInfo.get("violationcontent")))));
        emailContent.append("</br></br>");
        emailContent.append("<strong>备注：</strong>"+(ConvertUtil.convertToString(problemAlertInfo.get("description")).isEmpty() ? "无" : (ConvertUtil.convertToString(problemAlertInfo.get("description")))));
        emailContent.append("</br></br>");
        // 拼接附件列表
        emailContent.append(formatEmailAttachment(problemAlertInfo));
        emailContent.append("</br></br>");
        emailContent.append("请点击<a href=\""+bpaQualityImprovementCatalog+"\">此处</a>进入流程文档中心，查看《MQ-ES-16.7.5_CL8 质量改进流程评审要素》，质量改进相关任务活动要符合此文件要求。");
        emailContent.append("</div>");
        return emailContent.toString();
    }

    /**
     *  拼接表格附件
     *
     * @description:
     * @param service
     * @param entity
     * @author: hudueyong
     * @date: 2023年01月10日
     * @modify:
     */
    public String formatEmailAttachment(Map<String, Object> problemAlertInfo){
        StringBufferProxy sql = new StringBufferProxy();
        StringBuilder attachmentContent = new StringBuilder();
        sql.appendSingle("sourcetype = '{0}' and sourceid = '{1}'",QemProblemAlertEntity.tableName,problemAlertInfo.get("id"));
        CboAttachmentService cboAttachmentService =  (CboAttachmentService)SpringUtil.getBean("cboAttachmentService");
        List<CboAttachmentEntity> cboAttachmentEntities = cboAttachmentService.queryByWhere(sql.toString());
        if(cboAttachmentEntities.size()>0){
            // 可配置的url
            String qmsProbelmAlert = ParameterCache.getValue("qmsProbelmAlert");
            attachmentContent.append("该问题告警单包含附件(如下)，请登录系统进入<a href=\""+qmsProbelmAlert+"\">问题告警管理模块</a>查看。");
            attachmentContent.append("</br></br>");
            attachmentContent.append("<table border='1'  cellspacing='0' cellpadding='0' style='text-align: left;'></tableborder>");
            int index = 1;
            for(CboAttachmentEntity attachment : cboAttachmentEntities){
                attachmentContent.append("<tr><td align=\"center\" height=\"30px\" width=\"50px\">"+index+"</td>");
                attachmentContent.append("<td width=\"500px\">"+ attachment.getDisplayname()+"</td></tr>");
                index++;
            }
            attachmentContent.append("</table>");
            return attachmentContent.toString();
        } else {
            return "";
        }
    }

}
